package com.pipi.fanglan.dao;

import com.pipi.fanglan.model.form.ConfirmOrderForm;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pipi on 2017/7/16.
 */
@Component
public class CommitOrderDao {

    public boolean checkCommitSuccess(String result){
        boolean flag = false;
        return flag;
    }

    public String getCommitFormUrl(String html){
        Document doc = Jsoup.parse(html);
        Element selector = doc.getElementById("dealSelector");
        Element element = selector.children().first();
        String formUrl = element.val();
        return formUrl;
    }

    public ConfirmOrderForm getCommitParams(String html) {
        List<NameValuePair> list = new ArrayList<NameValuePair>(10);
        ConfirmOrderForm confirmOrderForm = new ConfirmOrderForm();
        Document doc = Jsoup.parse(html);


//        try{
//            doc = Jsoup.parse(new File("test.html"),"utf-8");
//        }catch (Exception e ){
//            e.printStackTrace();
//        }

        Element form = doc.getElementById("theform");
        confirmOrderForm.setUrl(form.attr("action"));
        Elements chirlren = form.children();
//        Element specialDiv = form.child(0);
//        Element hasNextTaskFlagInput = form.child(1);
//        Element btnDiv = form.child(2);
        Elements inputs = form.getElementsByTag("input");
//        ("input[type=hidden]")
        for(int i=0; i< inputs.size(); i++){
            Element input = inputs.get(i);
            BasicNameValuePair nameValuePair = new BasicNameValuePair(input.attr("name"),input.val());
            System.out.println(input.attr("name") + ": " + input.val());
            if("确认受理".equals(input.val())){
                String clickString = input.attr("onclick");
                String claimTaskUrl = clickString.substring(clickString.indexOf('='));
                confirmOrderForm.setPerformClaimTaskUrl(claimTaskUrl);
                continue;
            }
            list.add(nameValuePair);
        }
        confirmOrderForm.setParams(list);
        return confirmOrderForm;
    }
}
